/**
 扩展一个自定义的通用的后台管理模块
 **/

layui.define(['jquery', 'layer', 'element'], function(exports){
	var $ = layui.$ //重点处
    var layer = layui.layer;
    var element = layui.element;
    var popupRightIndex, popupCenterIndex, popupCenterParam;

    var sadmin = {

        // 设置侧栏折叠
        flexible: function (expand) {
            var isExapnd = $('.layui-layout-admin').hasClass('admin-nav-mini');
            if (isExapnd == !expand) {
                return;
            }
            if (expand) {
                $('.layui-layout-admin').removeClass('admin-nav-mini');
            } else {
                $('.layui-layout-admin').addClass('admin-nav-mini');
            }
        },
		// 路由注册
        initRouter: function () {
            // 自动扫描side菜单注册
            $('.layui-layout-admin .layui-side .layui-nav a[lay-href]').each(function () {
                var menuName = $(this).text();
                var menuPath = $(this).attr('lay-href');
                if ('javascript:;' != menuPath && '' != menuPath) {
                    var key = menuPath.replace(/[?:=&/]/g, '_');
                    //$(this).attr('href', '#!' + key);
					$(this).attr('href', 'javascript:;');
                    $(this).on("click", function(){
                        sadmin.loadView({
                            menuId: key,
                            menuPath: menuPath,
                            menuName: menuName
                        });
                    });
                } else {
                    $(this).attr('href', 'javascript:;');
                }
            });
        },
        // 加载主体部分
        loadView: function (param) {
            var menuId = param.menuId;
            var menuPath = param.menuPath;
            var menuName = param.menuName;
            var contentBody = '.layui-layout-admin .layui-body';

            if (menuName !== 'home_console' && menuName !== '控制台' && $("#menuName").length == 0) {
            	$('#desktop').after('<a id="menu" href="javascript:void(0);" class="frame-head" style="padding: 0 5px;"><cite id="menuName">'+menuName+'</cite></a>');
            }
            else if (menuName === '控制台') {
            	$("#menu").prev().remove();
            	$("#menu").remove();
            }
            else {
            	$("#menuName").html(menuName);
            }
            
            $('.layui-body.admin-iframe-body').removeClass('admin-iframe-body');
            sadmin.showLoading('.layui-layout-admin .layui-body');
            sadmin.ajax({
                url: menuPath,
                type: 'GET',
                dataType: 'html',
                success: function (result, status, xhr) {
                    $(contentBody).html(result);
                    sadmin.isRefresh = false;
                    element.render('breadcrumb');
                    sadmin.removeLoading('.layui-layout-admin .layui-body');
                    /*setTimeout(function() {
                        sadmin.removeLoading('.layui-layout-admin .layui-body');
                    }, 3000);*/

                }
            });
            // 移动设备切换页面隐藏侧导航
            if (document.body.clientWidth <= 750) {
                sadmin.flexible(true);
            }
        },
        // 设置导航栏选中
        activeNav: function (url) {
            $('.layui-layout-admin .layui-side .layui-nav .layui-nav-item .layui-nav-child dd').removeClass('layui-this');
            $('.layui-layout-admin .layui-side .layui-nav .layui-nav-item').removeClass('layui-this');
            if (url && url != '') {
                $('.layui-layout-admin .layui-side .layui-nav .layui-nav-item').removeClass('layui-nav-itemed');
                var $a = $('.layui-layout-admin .layui-side .layui-nav a[href="#!' + url + '"]');
                $a.parent('li').addClass('layui-this');
                $a.parent('dd').addClass('layui-this');
                $a.parent('dd').parent('.layui-nav-child').parent('.layui-nav-item').addClass('layui-nav-itemed');
            }
        },
        // 右侧弹出
        popupRight: function (path) {
            var param = new Object();
            param.path = path;
            param.id = 'adminPopupR';
            param.title = false;
            param.anim = 2;
            param.isOutAnim = false;
            param.closeBtn = false;
            param.offset = 'r';
            param.shadeClose = true;
            param.area = '336px';
            param.skin = 'layui-layer-adminRight';
            param.end = function () {
                layer.closeAll('tips');
            };
            popupRightIndex = sadmin.open(param);
            return popupRightIndex;
        },
        // 关闭右侧弹出
        closePopupRight: function () {
            layer.close(popupRightIndex);
        },
        // 中间弹出
        popupCenter: function (param) {
            param.id = 'adminPopupC';
            popupCenterParam = param;
            popupCenterIndex = sadmin.open(param);
            return popupCenterIndex;
        },
        // 关闭中间弹出并且触发finish回调
        finishPopupCenter: function () {
            layer.close(popupCenterIndex);
            popupCenterParam.finish ? popupCenterParam.finish() : '';
        },
        // 关闭中间弹出
        closePopupCenter: function () {
            layer.close(popupCenterIndex);
        },
        // 封装layer.open
        open: function (param) {
            var sCallBack = param.success;
            param.type = 1;
            param.area = param.area ? param.area : '450px';
            param.offset = param.offset ? param.offset : '120px';
            param.resize ? param.resize : false;
            param.shade ? param.shade : .2;
            param.success = function (layero, index) {
                sCallBack ? sCallBack(layero, index) : '';
                sadmin.ajax({
                    url: param.path,
                    type: 'GET',
                    dataType: 'html',
                    success: function (result, status, xhr) {
                        $(layero).children('.layui-layer-content').html(result);
                    }
                });
            };
            return layer.open(param);
        },
        // 封装ajax请求，返回数据类型为json
        req: function (url, data, success, method) {
            sadmin.ajax({
                url: url,
                data: data,
                type: method,
                dataType: 'json',
                success: success
            });
        },
        // 封装ajax请求
        ajax: function (param) {
            var successCallback = param.success;
            param.success = function (result, status, xhr) {
                // 判断登录过期和没有权限
                var jsonRs;
                if ('json' == param.dataType.toLowerCase()) {
                    jsonRs = result;
                } else if ('html' == param.dataType.toLowerCase() || 'text' == param.dataType.toLowerCase()) {
                    jsonRs = sadmin.parseJSON(result);
                }
                if (jsonRs) {
                    if (jsonRs.code == 401) {
                        layer.msg(jsonRs.msg, {icon: 2, time: 1500}, function () {
                            location.replace('/login');
                        }, 1000);
                        return;
                    } else if ('html' == paramdataType.toLowerCase() && jsonRs.code == 403) {
                        layer.msg(jsonRs.msg, {icon: 2});
                    }
                }
                successCallback(result, status, xhr);
            };
            param.error = function (xhr) {
                param.success({code: xhr.status, msg: xhr.statusText});
            };
            $.ajax(param);
        },
        // 判断是否为json
        parseJSON: function (str) {
            if (typeof str == 'string') {
                try {
                    var obj = JSON.parse(str);
                    if (typeof obj == 'object' && obj) {
                        return obj;
                    }
                } catch (e) {
                }
            }
        },
        // 显示加载动画
        showLoading: function (element) {
            /*$(element).append('<div class="page-loading"><div class="rubik-loader"></div></div>');*/

            $(element).append('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop admin-loading"></i>');
        },
        // 移除加载动画
        removeLoading: function (element) {
            $(element + '>.admin-loading').remove();
            /*$(element).children(".page-loading").remove()*/
        },
        // 缓存临时数据
        putTempData: function (key, value) {
            if (value) {
                layui.sessionData('tempData', {key: key, value: value});
            } else {
                layui.sessionData('tempData', {key: key, remove: true});
            }
        },
        // 获取缓存临时数据
        getTempData: function (key) {
            return layui.sessionData('tempData')[key];
        }
    };

    // ewAdmin提供的事件
    sadmin.events = {
        // 折叠侧导航
        flexible: function (e) {
            var expand = $('.layui-layout-admin').hasClass('admin-nav-mini');
            sadmin.flexible(expand);
        },
        // 设置主题
        theme: function () {
            sadmin.popupRight('home/theme.html');
        },
        // 全屏
        fullScreen: function (e) {
            var ac = 'layui-icon-screen-full', ic = 'layui-icon-screen-restore';
            var ti = $(this).find('i');

            var isFullscreen = document.fullscreenElement || document.msFullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || false;
            if (isFullscreen) {
                var efs = document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen || document.msExitFullscreen;
                if (efs) {
                    efs.call(document);
                } else if (window.ActiveXObject) {
                    var ws = new ActiveXObject('WScript.Shell');
                    ws && ws.SendKeys('{F11}');
                }
                ti.addClass(ac).removeClass(ic);
            } else {
                var el = document.documentElement;
                var rfs = el.requestFullscreen || el.webkitRequestFullscreen || el.mozRequestFullScreen || el.msRequestFullscreen;
                if (rfs) {
                    rfs.call(el);
                } else if (window.ActiveXObject) {
                    var ws = new ActiveXObject('WScript.Shell');
                    ws && ws.SendKeys('{F11}');
                }
                ti.addClass(ic).removeClass(ac);
            }
        },
        // 关闭所有弹窗
        closeDialog: function () {
            layer.closeAll('page');
        }
    };

    // 所有ew-event
    $('body').on('click', '*[ew-event]', function () {
        var event = $(this).attr('ew-event');
        var te = sadmin.events[event];
        te && te.call(this, $(this));
    });

    //输出接口
    exports('sadmin', sadmin);
});